package com.llh.uua.filter

import com.llh.uua.conf.properties.AppProperties
import com.llh.uua.util.JWT_AUTHORITY_KEY
import com.llh.uua.util.parseClaimsAccessToken
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 *
 * Created At 2021/3/24 20:56
 * @author llh
 */
@Component
class JwtFilter(private val appProperties: AppProperties) : OncePerRequestFilter() {
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain,
    ) {
        val token = request.getHeader(appProperties.jwt.header)
        if (!token.isNullOrEmpty()) {
            // 从签发的token中获取信息并进行“登录”操作

            val claims = parseClaimsAccessToken(token)
            val simpleAuthList = claims
                ?.get(JWT_AUTHORITY_KEY)
                ?.let { it as List<*> }
                ?.map { it.toString() }
                ?.map { SimpleGrantedAuthority(it) }
            val authentication = UsernamePasswordAuthenticationToken(
                claims?.subject, null, simpleAuthList)
            SecurityContextHolder.getContext().authentication = authentication
        }

        filterChain.doFilter(request, response)
    }


}